package cn.chiship.framework.upms.biz.system.service.impl;

import cn.chiship.framework.upms.biz.system.entity.UpmsNoticeExample;
import cn.chiship.framework.upms.biz.system.entity.UpmsNoticeSend;
import cn.chiship.framework.upms.biz.system.entity.UpmsNoticeSendExample;
import cn.chiship.framework.upms.biz.system.mapper.UpmsNoticeSendMapper;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsNoticeSystemDto;
import cn.chiship.framework.upms.biz.system.service.UpmsNoticeService;
import cn.chiship.framework.upms.core.enums.NoticePriorityEnums;
import cn.chiship.framework.upms.core.enums.NoticeScopeEnums;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.ObjectUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.upms.biz.system.entity.UpmsNotice;
import cn.chiship.framework.upms.biz.system.mapper.UpmsNoticeMapper;
import cn.chiship.sdk.framework.pojo.vo.OptionUser;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 通知公告表业务接口实现层 2021/10/22
 *
 * @author lijian
 */
@Service
public class UpmsNoticeServiceImpl extends BaseServiceImpl<UpmsNotice, UpmsNoticeExample> implements UpmsNoticeService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UpmsNoticeServiceImpl.class);

	private static final String SEND_SCOPE_ALL = "ALL";

	private static final String SEND_SCOPE_USER = "USER";

	private static final Byte SEND_STATUS_RELEASE = 1;

	private static final Byte SEND_STATUS_REVOKE = 2;

	@Resource
	UpmsNoticeMapper upmsNoticeMapper;

	@Resource
	UpmsNoticeSendMapper upmsNoticeSendMapper;

	@Override
	public BaseResult insertSelective(UpmsNotice upmsNotice) {
		upmsNotice.setStartTime(System.currentTimeMillis());
		upmsNotice.setSendTime(System.currentTimeMillis());
		upmsNotice.setSendStatus(Byte.valueOf("0"));
		return super.insertSelective(upmsNotice);
	}

	@Override
	public UpmsNotice selectByPrimaryKey(Object id) {
		UpmsNoticeExample noticeExample = new UpmsNoticeExample();
		noticeExample.createCriteria().andIdEqualTo(id.toString());
		List<UpmsNotice> notices = upmsNoticeMapper.selectByExampleWithBLOBs(noticeExample);
		if (notices.isEmpty()) {
			return null;
		}
		return notices.get(0);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public BaseResult deleteByExample(UpmsNoticeExample upmsNoticeExample) {

		List<String> noticeIds = new ArrayList<>();
		List<UpmsNotice> upmsNotices = upmsNoticeMapper.selectByExample(upmsNoticeExample);
		for (UpmsNotice notice : upmsNotices) {
			noticeIds.add(notice.getId());
		}
		if (!noticeIds.isEmpty()) {
			UpmsNoticeSendExample upmsNoticeSendExample = new UpmsNoticeSendExample();
			upmsNoticeSendExample.createCriteria().andNoticeIdIn(noticeIds);
			upmsNoticeSendMapper.deleteByExample(upmsNoticeSendExample);
		}
		super.deleteByExample(upmsNoticeExample);
		return BaseResult.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public BaseResult publish(String id, List<String> userIds) {
		if (StringUtil.isNull(userIds)) {
			userIds = new ArrayList<>();
		}
		UpmsNotice notice = upmsNoticeMapper.selectByPrimaryKey(id);
		notice.setSendStatus(SEND_STATUS_RELEASE);
		notice.setCancelTime(null);
		notice.setSendTime(System.currentTimeMillis());
		if (SEND_SCOPE_USER.equals(notice.getNoticeCategory()) && (!StringUtil.isNullOrEmpty(notice.getReceiver()))) {
			for (String item : Arrays.asList(notice.getReceiver().split(";"))) {
				userIds.add(item.split(":")[0]);
			}
		}
		if (!userIds.isEmpty()) {
			for (String userId : userIds) {
				UpmsNoticeSend upmsNoticeSend = new UpmsNoticeSend();
				upmsNoticeSend.setId(SnowflakeIdUtil.generateStrId());
				upmsNoticeSend.setGmtCreated(System.currentTimeMillis());
				upmsNoticeSend.setGmtModified(System.currentTimeMillis());
				upmsNoticeSend.setIsDeleted(BaseConstants.NO);
				upmsNoticeSend.setNoticeId(notice.getId());
				upmsNoticeSend.setUserId(userId);
				upmsNoticeSend.setReadFlag(Byte.valueOf("0"));
				upmsNoticeSend.setNoticeType(notice.getNoticeType());
				upmsNoticeSend.setNoticeUserType(notice.getNoticeUserType());
				upmsNoticeSendMapper.insertSelective(upmsNoticeSend);
			}
		}

		super.updateByPrimaryKeySelective(notice);
		return BaseResult.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public BaseResult sendSystemMsg(UpmsNoticeSystemDto upmsNoticeSystemDto) {
		if (StringUtil.isNullOrEmpty(upmsNoticeSystemDto.getUserId())) {
			return BaseResult.error("接收者不能为空！");
		}
		OptionUser optionUser = new OptionUser();
		optionUser.setOrgName("系统");
		optionUser.setRealName("自动发出");
		UpmsNotice upmsNotice = new UpmsNotice();
		upmsNotice.setStartTime(System.currentTimeMillis());
		upmsNotice.setSendTime(System.currentTimeMillis());
		upmsNotice.setNoticeTitle(upmsNoticeSystemDto.getTitle());
		upmsNotice.setNoticeAbstract(upmsNoticeSystemDto.getDesc());
		if (ObjectUtil.isNotEmpty(upmsNoticeSystemDto.getContent())) {
			upmsNotice.setNoticeContent(JSON.toJSONString(upmsNoticeSystemDto.getContent()));
		}
		upmsNotice.setReceiver(upmsNoticeSystemDto.getUserId() + ":" + upmsNoticeSystemDto.getRealName());
		upmsNotice.setNoticeUserType(upmsNoticeSystemDto.getUserTypeEnum().getType());
		upmsNotice.setNoticeCategory("USER");
		upmsNotice.setPriority(upmsNoticeSystemDto.getNoticePriorityEnums().getType());
		upmsNotice.setModuleType(upmsNoticeSystemDto.getNoticeModuleTypeEnums().getType());
		upmsNotice.setSendStatus(Byte.valueOf("1"));
		upmsNotice.setSender(JSON.toJSONString(optionUser));
		upmsNotice.setCreatedBy(JSON.toJSONString(optionUser));
		upmsNotice.setCreatedUserId("0");
		upmsNotice.setCreatedOrgId("0");
		upmsNotice.setNoticeType(Byte.valueOf("2"));
		super.insertSelective(upmsNotice);

		UpmsNoticeSend upmsNoticeSend = new UpmsNoticeSend();
		upmsNoticeSend.setId(SnowflakeIdUtil.generateStrId());
		upmsNoticeSend.setGmtCreated(System.currentTimeMillis());
		upmsNoticeSend.setGmtModified(System.currentTimeMillis());
		upmsNoticeSend.setIsDeleted(BaseConstants.NO);
		upmsNoticeSend.setNoticeId(upmsNotice.getId());
		upmsNoticeSend.setUserId(upmsNoticeSystemDto.getUserId());
		upmsNoticeSend.setReadFlag(Byte.valueOf("0"));
		upmsNoticeSend.setNoticeType(upmsNotice.getNoticeType());
		upmsNoticeSend.setNoticeUserType(upmsNotice.getNoticeUserType());
		upmsNoticeSendMapper.insertSelective(upmsNoticeSend);
		return BaseResult.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public BaseResult revoke(String id) {
		UpmsNotice notice = upmsNoticeMapper.selectByPrimaryKey(id);
		notice.setSendStatus(SEND_STATUS_REVOKE);
		notice.setCancelTime(System.currentTimeMillis());
		UpmsNoticeSendExample upmsNoticeSendExample = new UpmsNoticeSendExample();
		upmsNoticeSendExample.createCriteria().andNoticeIdEqualTo(notice.getId());
		upmsNoticeSendMapper.deleteByExample(upmsNoticeSendExample);
		super.updateByPrimaryKeySelective(notice);

		return BaseResult.ok();
	}

}
